import Axios from "axios";
import { typeCheck } from "./util";

const instance = Axios.create({
  // baseURL: "http://music.mendada.cn/api",
  baseURL: "http://localhost:3000/api",
  withCredentials: true
});
instance.interceptors.response.use(
  function(response) {
    return response.data;
  },
  function(error) {
    // 301需要登录
    if (error.response.status === 301) {
      let referer = location.href;
      location.replace("/login?referer=" + encodeURIComponent(referer));
    }
    return Promise.resolve(error.response.data);
  }
);

export const get = function(url, params = {}, config = {}) {
  return instance
    .get(url, {
      ...config,
      params
    })
    .catch(e => {
      throw e;
    });
};

export const fetchData = function({ urls=[], datas=[], configs=[] }) {
  if (urls && !Array.isArray(urls)) {
    throw "urls必须是一个Array,但是传入的是" + typeCheck(urls);
  }
  if (datas && !Array.isArray(datas)) {
    throw "datas必须是一个Array,但是传入的是" + typeCheck(datas);
  }
  if (configs && !Array.isArray(configs)) {
    throw "configs必须是一个Array,但是传入的是" + typeCheck(configs);
  }
  let fetchs = [];
  urls.forEach((url, ind) => {
    if (typeof url !== "string") {
      throw `urls每一项都应为string，但是第${ind}项是${typeCheck(url)}`;
    }
    let data = datas[ind],
      config = configs[ind];
    if (data && typeCheck(data) !== "[object Object]") {
      throw `data每一项应该是对象，但是第${ind}项是${typeCheck(data)}`;
    }
    if (config && typeCheck(config) !== "[object Object]") {
      throw `config每一项应该是对象，但是第${ind}项是${typeCheck(config)}`;
    }
    fetchs.push(get(url, data, config));
  });

  return Promise.all(fetchs).catch(e=>{
      console.log(e.message)
  })
};
